<template>
  <div>
    <el-dialog v-model="showDialog" :title="title" width="50%" center>
      <el-form :model="dictDTO" ref="dictDTORef" :label-width="100" label-position="left">
        <el-form-item label="字典名称" prop="dictName" :rules="required">
          <el-input v-model="dictDTO.dictName" placeholder="字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="dictCode" :rules="required">
          <el-input v-model="dictDTO.dictCode" placeholder="字典编码" />
        </el-form-item>
        <el-form-item label="字典描述" prop="dictDesc" :rules="required">
          <el-input v-model="dictDTO.dictDesc" placeholder="字典描述" />
        </el-form-item>
        <el-form-item label="系统默认" prop="systemFlag" :rules="required">
          <el-switch v-model="dictDTO.systemFlag" inactive-value="0" active-value="1" inline-prompt active-text="是" inactive-text="否" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="switchDialog()"> 取 消 </el-button>
          <el-button type="primary" @click="submitForm">提 交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { QuestionFilled } from '@element-plus/icons-vue'
import Dict from '@/api/sys/dict'
import { required, limitMaxMin, letter } from '@/utils/FormRule'
import { deepClone } from '@/utils'
import useStore from '@/store'

const { dictStore } = useStore()

onMounted(() => {})

defineProps({})

// 弹框开关
const showDialog = ref(false)

// 是否更新，false为新增弹框，true为修改弹框
const isEdit = ref(false)

// 弹框标题
const title = computed(() => (isEdit.value ? '修改字典' : '新增字典'))

// 字典参数
const dictDTO = ref({})

// 字典表单ref
const dictDTORef = ref()

const emits = defineEmits(['success'])

// 提交表单之前先验证
function submitForm() {
  // 表单验证, 如果是菜单，则需要验证字典和菜单两个表单
  dictDTORef.value.validate((valid) => {
    if (valid) {
      if (isEdit.value) {
        update()
      } else {
        add()
      }
    }
  })
}

// 新增一个字典
function add() {
  Dict.create(dictDTO.value).then(() => {
    emits('success')
    switchDialog()
    dictStore.initDict()
  })
}

// 更新字典信息
function update() {
  Dict.update(dictDTO.value).then(() => {
    emits('success')
    switchDialog()
    dictStore.initDict()
  })
}

/**
 * 弹框的打开与关闭
 * @param edit true编辑, false新增
 * @param dict 需要编辑的字典信息，
 */
function switchDialog(edit, dict) {
  // 先判断是新增还是修改
  isEdit.value = edit
  if (dict) {
    dictDTO.value = deepClone(dict)
    dictDTO.value.systemFlag = dict.systemFlag + ''
  } else {
    // 弹框关闭清空数据
    if (dictDTORef.value !== undefined) {
      dictDTORef.value.resetFields()
    }
    isEdit.value = false
  }
  showDialog.value = !showDialog.value
}

defineExpose({ switchDialog })
</script>

<style lang="scss" scoped>
label {
  font-weight: normal;
}
</style>
